﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using IMLibrary.NetClient;
 
namespace IMLibrary.Server
{
    /// <summary>
    /// UDP中转服务
    /// </summary>
    public class UDPTurnServer
    {
        #region 属性
        /// <summary>
        /// 服务端口
        /// </summary>
        public Int32  Port
        {
            private set;
            get;
        }
        /// <summary>
        /// 数据接收者Client IPEndPoint
        /// </summary>
        public IPEndPoint ClientIPEndPoint = null;
        /// <summary>
        /// 最后活动时间
        /// </summary>
        public DateTime LastActiveTime
        {
            private set;
            get;
        }
        /// <summary>
        /// UDP套接字服务
        /// </summary>
        public SockUDPV1 sockUdp = null;
        /// <summary>
        /// 接收数据的对端
        /// </summary>
        public UDPTurnServer RemoteClient = null;
        #endregion
         
        #region 公共方法
        /// <summary>
        /// 启动服务
        /// </summary>
        public void Start()
        {
            sockUdp = new SockUDPV1();
            sockUdp.IsAsync = true  ;//标明异步通信
            sockUdp.Blocking = false ;//非阻止模式
            sockUdp.Listen(0);
            Port = sockUdp.ListenPort;
            LastActiveTime = DateTime.Now;

            sockUdp.DataArrival += (sender, e) =>
            {
                if (ClientIPEndPoint == null)
                {
                    ClientIPEndPoint = e.RemoteIPEndPoint;
                    sockUdp.socket.Connect(ClientIPEndPoint);
                }
                if (RemoteClient != null)
                {
                    RemoteClient.sendData(e.Data);
                    LastActiveTime = DateTime.Now;
                }
            };
        }

        /// <summary>
        /// 关闭服务并释放资源
        /// </summary>
        public void Close()
        {
            if (sockUdp != null && sockUdp.Listened)
                sockUdp.CloseSock();
        }

        /// <summary>
        /// 向客户端发送数据
        /// </summary>
        /// <param name="data"></param>
        public void sendData(byte[] data)
        {
            if (ClientIPEndPoint != null)
            {
                sockUdp.socket.Send(data);
                LastActiveTime = DateTime.Now;
            }
        }
        #endregion
    }
}
